package com.roc.web.action.settlemorg;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.ApplyChannel;
import com.roc.bean.OrgSettlementBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.TblSettleItem;
import com.roc.service.IAccountBalanceService;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.service.org.IOrgMoneyService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OrgPayStatus;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/applyMoneyOrg")
public class SettlementOrgMoneyAction extends PaginationBaseAction{
	private static final long serialVersionUID = 1L;
	private SettlementOrgMoneySearchCondition searchCondition;
	private static Logger logger = LogManager.getLogger(SettlementOrgMoneyAction.class);
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	private String[] multiSel;
	private List<ApplyChannel> channelList;
	@Autowired
	private IPagenitionService pagenitionService;
	@Autowired
	private IOrgMoneyService applyService;
	@Autowired
	private IAccountBalanceService service;
	/**
	 * 初始化待出款页面
	 * @return
	 */
	@Action(value="queryApplyMoneyInit",results={@Result(name="success",location="/pages/settlementOrg/orgMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryMakeMoneyJsp(){
		try {
			Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				searchCondition=new SettlementOrgMoneySearchCondition();
				String today = Constance.currTime();
				searchCondition.setApplyDateMin(today);
				searchCondition.setApplyDateMax(today);
				channelList=applyService.selectChannelList();
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionError("初始化出款页面异常");
			return ERROR;
		}
		return ERROR;		
	}
	/**
	 * 待出款列表
	 * @return
	 */
	@Action(value="queryApplyMoneyJsp",results={@Result(name="success",location="/pages/settlementOrg/orgMoneyList.jsp")})
	public String querySettlementMsgList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementOrgMoneySearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementOrgMoneySearchCondition();
					}
				}
				channelList=applyService.selectChannelList();
				List<TblInsInf> queryOrgList= service.loadOrgCode();
				if(queryOrgList!=null){
					orgList.addAll(queryOrgList);
				}
				String message=null;
				Map<String,Object> resultMap=null;
				//首先处理拼凑问题
				if(Constance.isNotEmpty(searchCondition.getAmtMax()) && "retry".equals(searchCondition.getCombineFlag())){//条件存在并且拼凑
					applyService.clearOriginCombie(searchCondition,op);
					resultMap=applyService.handleCombineAmt(searchCondition,op);
					if(resultMap.containsKey("result")){
							message=resultMap.get("result").toString();
							searchCondition.setCombingName(op.getAccountNo());//设置标记
							searchCondition.setCombineFlag("exists");
						}					
				}					
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			
			List<OrgSettlementBean> settleList = new ArrayList<OrgSettlementBean>();
			double amt=0,part=0;
			dealTheSearchRsList(searchRsList,settleList);
			if(message==null){
				DecimalFormat df=new DecimalFormat("0.00");
				message="已统计出记录"+rows+"条，";
				for(OrgSettlementBean item:settleList){//筛选的当前页面总金额
					amt=amt+item.getAmt();
				}				
				message=message+"当前页面金额:"+df.format(amt)+"元，";	
				
				List<Object> other=pagenitionService.findAllSQL(searchCondition,0,rows);
				for(Object object:other){//的总金额
					Object[] o=(Object[]) object;
					part=part+Double.valueOf(Constance.Null2EmptyTrim(o[7]));
				}
				message=message+"累计总金额:"+df.format(part)+"元";
			}
			addActionMessage(message);			
			getRequest().setAttribute("settleList", settleList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);			
			return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("待出款查询异常");
			return ERROR;
		}
		return ERROR;
	}
	private void dealTheSearchRsList(List<Object> searchRsList,
			List<OrgSettlementBean> settleList) throws Exception {
		try {
			if(searchRsList != null && searchRsList.size() > 0){
				Iterator<Object> it = searchRsList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();					
					OrgSettlementBean bean=new OrgSettlementBean();
					bean.setSettleDate(Constance.Null2EmptyTrim(obj[0]));
					bean.setKeyRsp(Constance.Null2EmptyTrim(obj[1]));
					bean.setTransCd(OrgPayStatus.valueOfCode(Constance.Null2EmptyTrim(obj[2])).getName());
					bean.setOrgCode(Constance.Null2EmptyTrim(obj[3]));
					bean.setAccountNo(Constance.Null2EmptyTrim(obj[4]));
					bean.setMobileNo(Constance.Null2EmptyTrim(obj[5]));
					String num=Constance.Null2EmptyTrim(obj[6]);
					if(!"".equals(num)){
						bean.setTotalNum(Integer.parseInt(num));
					}else{
						bean.setTotalNum(1);
					}
					String amt=Constance.Null2EmptyTrim(obj[7]);
					if(!"".equals(amt)){
						bean.setAmt(Double.parseDouble(amt));
					}else{
						bean.setAmt(0.00);
					}
					String fee=Constance.Null2EmptyTrim(obj[8]);
					if(!"".equals(fee)){
						bean.setFee(Double.parseDouble(fee));
					}else{
						bean.setFee(0.00);
					}
					bean.setAcctNo(Constance.Null2EmptyTrim(obj[9]));
					bean.setAcctName(Constance.Null2EmptyTrim(obj[10]));
					bean.setStatus(OrgPayStatus.valueOfCode(Constance.Null2EmptyTrim(obj[11])).getName());
					bean.setBankName(Constance.Null2EmptyTrim(obj[12]));
					if(bean.getAcctName().length()>5 && !bean.getAcctName().contains("·")){
						bean.setNature("对公");
					}else if(bean.getAcctName().length()==5){
						bean.setNature("未知");
					}else{
						bean.setNature("对私");
					}
					settleList.add(bean);					
				}
			}
		}catch (Exception e) {
			throw new Exception("解析数据封装到待出款信息实体类异常");
		}
	}
	
	/**
	 * 出款申请
	 * @return
	 */
	@Action(value="applyMoneyInit",results={@Result(name="success",location="/pages/settlementOrg/orgMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String applyMoneyList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				Map<String,Object> resultMap=null;
				//首先处理拼凑问题
				if(Constance.isNotEmpty(searchCondition.getAmtMax()) && "retry".equals(searchCondition.getCombineFlag())){//条件存在并且拼凑
					applyService.clearOriginCombie(searchCondition,op);
					resultMap=applyService.handleCombineAmt(searchCondition,op);
					if(resultMap.containsKey("result")){
							searchCondition.setCombingName(op.getAccountNo());//设置标记
							searchCondition.setCombineFlag("exists");
						}
				}
			channelList=applyService.selectChannelList();
			List<TblInsInf> queryOrgList= service.loadOrgCode();
			if(queryOrgList!=null){
				orgList.addAll(queryOrgList);
			}
			String msg=applyService.applySettlementMoney(searchCondition,op);
			addActionMessage(msg);
			return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("请求出款异常");
			return ERROR;
		}
		return ERROR;
	}
	/**
	 * 出款申请(复选框模式)
	 * @return
	 */
	@Action(value="applyMoneySimpleInit",results={@Result(name="success",location="/pages/settlementOrg/orgMoneyList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String applyMoneyListSimple(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
			channelList=applyService.selectChannelList();
			List<TblInsInf> queryOrgList= service.loadOrgCode();
			if(queryOrgList!=null){
				orgList.addAll(queryOrgList);
			}
			String msg=applyService.applySettlementMoneySimple(searchCondition,multiSel,op);
			addActionMessage(msg);
			return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error("部分请求出款异常",e);
			addActionMessage("请求出款异常");
			return ERROR;
		}
		return ERROR;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ORG_MONEY_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettlementOrgMoneySearchCondition)getSession().getAttribute(SEARCH_SESSION_ORG_MONEY_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public SettlementOrgMoneySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			SettlementOrgMoneySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public String[] getMultiSel() {
		return multiSel;
	}
	public void setMultiSel(String[] multiSel) {
		this.multiSel = multiSel;
	}
	
	
	public List<ApplyChannel> getChannelList() {
		return channelList;
	}
	public void setChannelList(List<ApplyChannel> channelList) {
		this.channelList = channelList;
	}
	public List<TblInsInf> getOrgList() {
		return orgList;
	}
	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}
	
}
